#!/usr/bin/env python
# -*- coding: utf-8 -*-

from teamupshoppers import app
from flask          import Flask, views, jsonify, render_template, request, session, flash, url_for, redirect, g
from werkzeug       import check_password_hash, generate_password_hash
from db             import DB

import logging

"""Registers the user."""
class Register(views.MethodView):
    def get_user_id(self, username):
        """Convenience method to look up the id for a username."""
        __db = DB()
        rv = __db.query('''select user_id from user where username = ?''', username )
        return rv[0] if rv else None
        
    def post(self):
        logging.warning('1') 
        if g.user:
            logging.warning('2') 
            return redirect(url_for('index'))
        error = None
        logging.warning('3') 
        if request.method == 'POST':
            logging.warning('4') 
            if not request.form['username']:
                error = 'You have to enter a username'
            elif not request.form['email'] or '@' not in request.form['email']:
                error = 'You have to enter a valid email address'
            elif not request.form['password']:
                error = 'You have to enter a password'
            elif request.form['password'] != request.form['password2']:
                error = 'The two passwords do not match'
            elif self.get_user_id( [request.form['username']]) is not None:
                error = 'The username is already taken'
            else:
                logging.warning('5') 
                pw_hash = generate_password_hash(request.form['password'])
                _db = DB()
                _db.execute('''insert into user    (name, email, pw_hash)
                                            values  (?, ?, ?)''',
                            [ request.form['username'], request.form['email'], pw_hash]
                            )
                error = 'You were successfully registered and can login now'
            flash( error )
        return redirect(url_for('main'))
